function rois = zoomrois2(s,nrois,plotting)

% rois = zoomrois1 returns indeces of interest from zooming
%INPUT:     s = scan-structure such as read in by scanread.m
%       nrois = number of ROIs you would like to apply
%    plotting = plots the integrated scans if set to 1
%OUTPUT: structure 'rois' containing:
%        -indices: matrix indices of the defined ROI (to be used to sum over for obtaining the spectrum)
%        -data:    integrated scan using rois.indices
%        -datan:   integrated scan using rois.indices normalized by monitor
%                  from Specfile
%        -datae:   error (poisson counting)
%        -dataen:  normalized error
%        -cenom:   center of mask (Tuomas: 'more usefull for position than gaussian fit')

try logscaling;
catch
    logscaling = 1;
end

if nargin<3
    plotting = 0;
end

limmax = size(s.A,2);

for i=1:nrois
    if logscaling
        imagesc(log(sumx(s.A)))
    else
        imagesc(sumx(s.A))
    end
    axis square
    zoom on
    title('Zoom figure around region of interest and press Return');
    fprintf('%i/%i: Zoom around ROI, then focus back on this window and press Return',i,nrois)
    pause
    limits = round(axis);
    limits(limits < 1) = 1; limits(limits > limmax) = limmax;

    T = zeros(size(s.A,2),size(s.A,3));
    T(limits(3):limits(4),:) = 1;
    t = zeros(size(s.A,2),size(s.A,3));
    t(:,limits(1):limits(2)) = 1;

    rois(i).indices = find(t.*T == 1);
end

%read in scan for instant plotting
for h=1:length(rois)
    for l=1:size(s.A,1)
        rois(h).data(l) = sumy(s.A(l,rois(h).indices));
        rois(h).datan(l) = sqrt(sumy(s.A(l,rois(h).indices)));
        rois(h).datae(l) = sumy(s.A(l,rois(h).indices))./s.monitor(l);
        rois(h).dataen(l) = sqrt(sumy(s.A(l,rois(h).indices)))./s.monitor(l);
    end
end

for n=1:length(rois)
    rois(n).cenom = trapz(s.energy_cc,rois(n).data'.*s.energy_cc)./trapz(s.energy_cc,rois(n).data');
end

if plotting
figure
    subplot(3,3,1)
        plot(s.energy_cc,rois.datan(:,1))
        legend('ROI 1')
    subplot(3,3,2)
        plot(s.energy_cc,rois.datan(:,2))
        legend('ROI 2')
    subplot(3,3,3)
        plot(s.energy_cc,rois.datan(:,3))
        legend('ROI 3')
    subplot(3,3,4)
        plot(s.energy_cc,rois.datan(:,4))
        legend('ROI 4')
    subplot(3,3,5)
        plot(s.energy_cc,rois.datan(:,5))
        legend('ROI 5')
    subplot(3,3,6)
        plot(s.energy_cc,rois.datan(:,6))
        legend('ROI 6')
    subplot(3,3,7)
        plot(s.energy_cc,rois.datan(:,7))
        legend('ROI 7')
    subplot(3,3,8)
        plot(s.energy_cc,rois.datan(:,8))
        legend('ROI 8')
    subplot(3,3,9)
        plot(s.energy_cc,rois.datan(:,9))
        legend('ROI 9')
end

